<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>选择药品</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", "Helvetica Neue", Arial, sans-serif; background: #FFFFFF; color: var(--text-primary); font-size: 14px; line-height: 1.5; }
        :root { --primary:#0F6CBD; --primary-dark:#0A4F8D; --text-primary:#1A1A1A; --text-secondary:#4D4D4D; --text-tertiary:#767676; --border-light:#F0F0F0; --border-normal:#E0E0E0; --bg-primary:#FFFFFF; --bg-secondary:#F9F9F9; --spacing-8:8px; --spacing-12:12px; --spacing-16:16px; --spacing-24:24px; --font-body:14px; --font-page-title:20px; --font-table-title:14px; --font-table:13px; --font-small:12px; --radius-small:2px; }
        .modal { width: 100vw; height: 100vh; display: flex; flex-direction: column; background: var(--bg-primary); }
        .modal-header { padding: var(--spacing-16) var(--spacing-24); border-bottom: 1px solid var(--border-light); display: flex; justify-content: space-between; align-items: center; }
        .modal-title { font-size: var(--font-page-title); font-weight: 600; color: var(--text-primary); }
        .modal-close { background: none; border: none; cursor: pointer; color: var(--text-tertiary); font-size: 20px; width: 32px; height: 32px; border-radius: var(--radius-small); }
        .modal-close:hover { background-color: var(--bg-secondary); color: var(--text-secondary); }
        /* 头部与动作区（对齐15页添加药品弹窗） */
        .add-drug-header { padding: var(--spacing-24); border-bottom: 1px solid var(--border-light); background: var(--bg-primary); display: flex; justify-content: space-between; align-items: center; }
        .page-title { font-size: var(--font-page-title); font-weight: 600; color: var(--text-primary); }
        .add-drug-header-actions { display: flex; align-items: center; gap: var(--spacing-16); }
        .search-box { position: relative; width: 240px; }
        .search-box input { width: 100%; height: 32px; padding: 8px 8px 8px 32px; border: 1px solid var(--border-normal); border-radius: var(--radius-small); font-size: var(--font-body); color: var(--text-primary); }
        .search-icon { position: absolute; left: 8px; top: 50%; transform: translateY(-50%); color: var(--text-tertiary); }
        .filter-select { height: 32px; border: 1px solid var(--border-normal); border-radius: var(--radius-small); padding: 0 var(--spacing-12); font-size: var(--font-body); color: var(--text-primary); background: var(--bg-primary); }
        .btn { padding: 8px 16px; border-radius: var(--radius-small); font-size: var(--font-body); font-weight: 500; cursor: pointer; border: none; display: inline-flex; align-items: center; justify-content: center; transition: all 0.2s; height: 32px; }
        .btn-primary { background: var(--primary); color: #fff; }
        .btn-primary:hover { background: var(--primary-dark); }
        .btn-default { background: var(--bg-primary); color: var(--text-secondary); border: 1px solid var(--border-normal); }
        .btn-default:hover { background: var(--bg-secondary); }
        .body { flex: 1; display: flex; overflow: hidden; }
        .add-drug-left { width: 280px; background: var(--bg-primary); border-right: 1px solid var(--border-light); display: flex; flex-direction: column; }
        .add-drug-left-header { padding: var(--spacing-16); border-bottom: 1px solid var(--border-light); }
        .add-drug-search { position: relative; height: 32px; }
        .add-drug-search input { width: 100%; height: 32px; padding: 8px 8px 8px 32px; border: 1px solid var(--border-normal); border-radius: var(--radius-small); }
        .add-drug-category-tree { flex: 1; overflow: auto; padding: var(--spacing-12); }
        .category-item { padding: 8px 12px; border-radius: var(--radius-small); cursor: pointer; display: flex; align-items: center; gap: 8px; }
        .category-item:hover { background: var(--bg-secondary); }
        .category-item.active { background: #D0E7FF; color: var(--primary); font-weight: 500; }
        .add-drug-right { flex: 1; display: flex; flex-direction: column; overflow: hidden; }
        .add-drug-list-container { flex: 1; display: flex; flex-direction: column; padding: var(--spacing-24); overflow: hidden; }
        .add-drug-list-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: var(--spacing-16); }
        .add-drug-selected-count { color: var(--text-secondary); font-weight: 500; }
        .add-drug-table-container { flex: 1; overflow: auto; border: 1px solid var(--border-light); border-radius: var(--radius-small); background: var(--bg-primary); }
        .add-drug-table { width: 100%; border-collapse: collapse; min-width: 1200px; }
        .add-drug-table th { position: sticky; top: 0; z-index: 1; background: var(--bg-secondary); padding: 12px 16px; text-align: left; font-weight: 600; color: var(--text-secondary); border-bottom: 1px solid var(--border-normal); height: 40px; font-size: var(--font-table-title); white-space: nowrap; }
        .add-drug-table td { padding: 12px 16px; border-bottom: 1px solid var(--border-light); color: var(--text-secondary); height: 40px; font-size: var(--font-table); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .operations { display: inline-flex; gap: 8px; }
        .add-drug-pagination { display: flex; justify-content: space-between; align-items: center; padding: var(--spacing-16); border-top: 1px solid var(--border-light); background: var(--bg-primary); }
        .page-numbers { display: flex; gap: 8px; }
        .page-numbers button { min-width: 32px; height: 32px; border-radius: var(--radius-small); border: 1px solid var(--border-normal); background: var(--bg-primary); cursor: pointer; color: var(--text-secondary); }
        .page-numbers button.active { background: var(--primary); border-color: var(--primary); color: #fff; }
        .pagination-size { display: flex; align-items: center; gap: 8px; font-size: var(--font-small); color: var(--text-secondary); }
        .page-size-selector { height: 32px; border: 1px solid var(--border-normal); border-radius: var(--radius-small); padding: 0 8px; }
        .add-drug-actions { padding: var(--spacing-16) var(--spacing-24); border-top: 1px solid var(--border-light); display: flex; justify-content: flex-end; gap: var(--spacing-16); background: var(--bg-primary); }
        .checkbox { width: 16px; height: 16px; accent-color: var(--primary); }
        .operation-link { color: var(--primary); cursor: pointer; text-decoration: none; }
        .operation-link:hover { color: var(--primary-dark); }
        .modal-overlay { position: fixed; top:0; left:0; right:0; bottom:0; background-color: rgba(0,0,0,0.5); display: none; align-items: center; justify-content: center; z-index: 2000; }
        .dialog { background: var(--bg-primary); border: 1px solid var(--border-light); border-radius: var(--radius-small); box-shadow: 0 4px 16px rgba(0,0,0,0.15); width: 720px; max-width: 90%; max-height: 85vh; display: flex; flex-direction: column; overflow: hidden; }
        .dialog .modal-header { border-bottom: 1px solid var(--border-light); }
        .dialog .modal-body { padding: var(--spacing-24); overflow: auto; }
        .detail-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--spacing-16) var(--spacing-24); }
        .detail-item { display: flex; flex-direction: column; }
        .detail-label { color: var(--text-tertiary); font-size: var(--font-small); margin-bottom: 4px; }
        .detail-value { color: var(--text-primary); font-size: var(--font-body); }
    </style>
</head>
<body>
    <div class="modal">
        <div class="modal-header">
            <div class="modal-title" aria-hidden="true"></div>
            <button class="modal-close" id="btnClose">×</button>
        </div>
        <div class="add-drug-header">
            <div class="page-title">选择药品</div>
            <div class="add-drug-header-actions">
                <div class="search-box">
                    <svg class="search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                    <input id="kw" type="text" placeholder="搜索药品/编码...">
                </div>
                <select id="basicFilter" class="filter-select">
                    <option value="all">基本药物: 全部</option>
                    <option value="yes">是</option>
                    <option value="no">否</option>
                </select>
                <select id="formFilter" class="filter-select">
                    <option value="all">剂型: 全部</option>
                    <option value="片剂">片剂</option>
                    <option value="胶囊">胶囊</option>
                    <option value="注射剂">注射剂</option>
                    <option value="液体剂">液体剂</option>
                    <option value="颗粒剂">颗粒剂</option>
                </select>
                <button id="btnQuery" class="btn btn-primary">查询</button>
                <button id="btnReset" class="btn btn-default">重置</button>
            </div>
        </div>
        <div class="body">
            <div class="add-drug-left">
                <div class="add-drug-left-header">
                    <div class="add-drug-search">
                        <svg class="search-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                        <input id="catKw" type="text" placeholder="搜索分类...">
                    </div>
                </div>
                <div id="catList" class="add-drug-category-tree"></div>
            </div>
            <div class="add-drug-right">
                <div class="add-drug-list-container">
                    <div class="add-drug-list-header"><div class="add-drug-selected-count">已选择: <span id="selectedCount">0</span> 项</div></div>
                    <div class="add-drug-table-container">
                    <table class="add-drug-table">
                        <thead>
                            <tr>
                                <th style="width:60px;">选择</th>
                                <th>药品名称</th>
                                <th>药品编码</th>
                                <th>规格</th>
                                <th>剂型</th>
                                <th>单位</th>
                                <th>基本药物</th>
                                <th>常用用法</th>
                                <th>常用用量</th>
                                <th>常用频次</th>
                                <th>单价</th>
                                <th>适应症</th>
                                <th>禁忌症</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="tbody"></tbody>
                    </table>
                    </div>
                    <div class="add-drug-pagination">
                        <div class="add-drug-pagination-text">共 <span id="total">0</span> 条记录</div>
                        <div class="add-drug-pagination-controls" style="display:flex; align-items:center; gap:16px;">
                            <div id="pages" class="page-numbers"></div>
                            <div class="pagination-size">每页显示
                                <select id="psel" class="page-size-selector">
                                    <option value="10">10</option>
                                    <option value="20">20</option>
                                    <option value="50">50</option>
                                </select> 条
                            </div>
                        </div>
                    </div>
                    <div class="add-drug-actions">
                        <button id="btnCancel" class="btn btn-default">取消</button>
                        <button id="btnOk" class="btn btn-primary" disabled>确认添加</button>
                    </div>
                </div>
            </div>
        </div>
        
    </div>
    <script>
        (function(){
            // 模拟从父页面或本地获取个人药品库数据（字段与15页个人药品列表一致）
            let personalDrugs = (window.opener && window.opener.__PERSONAL_DRUGS__) || [
                { id:1, name:'阿莫西林', code:'AM001', spec:'0.25g/片', form:'片剂', unit:'片', isBasic:true, usage:'口服', dosage:'0.25g/次', frequency:'3次/日', price:'0.80', indications:'呼吸道感染', contraindications:'过敏史', categoryId:311 },
                { id:2, name:'头孢克洛', code:'TB002', spec:'0.25g/片', form:'片剂', unit:'片', isBasic:true, usage:'口服', dosage:'0.25g/次', frequency:'2次/日', price:'1.20', indications:'细菌感染', contraindications:'肾功能不全', categoryId:312 },
                { id:3, name:'布洛芬', code:'BL003', spec:'0.2g/片', form:'片剂', unit:'片', isBasic:true, usage:'口服', dosage:'0.2g/次', frequency:'3次/日', price:'0.30', indications:'发热镇痛', contraindications:'胃溃疡', categoryId:4 },
                { id:4, name:'板蓝根', code:'BL005', spec:'10g/袋', form:'颗粒剂', unit:'袋', isBasic:true, usage:'冲服', dosage:'10g/次', frequency:'3次/日', price:'0.90', indications:'感冒发热', contraindications:'孕妇慎用', categoryId:122 }
            ];

            // 分类树（精简，保持与15页风格一致）
            const categories = [
                { id:1, name:'心脑血管药物', children:[ {id:11,name:'降压药'}, {id:12,name:'抗血小板药'}, {id:13,name:'抗凝药'} ] },
                { id:2, name:'消化系统药物', children:[ {id:21,name:'抑酸药'}, {id:22,name:'促胃动力药'}, {id:23,name:'止泻与通便'} ] },
                { id:3, name:'抗感染药物', children:[ {id:31,name:'抗生素类',children:[{id:311,name:'青霉素类'},{id:312,name:'头孢菌素类'},{id:313,name:'大环内酯类'}]}, {id:32,name:'抗病毒药'}, {id:33,name:'抗真菌药'} ] },
                { id:4, name:'解热镇痛药', children:[ {id:41,name:'NSAIDs'}, {id:42,name:'解热镇痛复方'} ] },
                { id:5, name:'呼吸系统药物', children:[ {id:51,name:'镇咳祛痰'}, {id:52,name:'支气管扩张'}, {id:53,name:'抗过敏'} ] },
                { id:6, name:'内分泌系统药物', children:[ {id:61,name:'降糖药'}, {id:62,name:'甲状腺药物'} ] },
                { id:7, name:'神经系统药物', children:[ {id:71,name:'镇静催眠'}, {id:72,name:'抗癫痫'} ] },
                { id:8, name:'血液系统药物', children:[ {id:81,name:'造血药'}, {id:82,name:'止血与抗纤溶'} ] },
                { id:9, name:'维生素及营养药', children:[ {id:91,name:'维生素'}, {id:92,name:'矿物质'} ] },
                { id:10, name:'皮肤科用药', children:[ {id:101,name:'抗感染'}, {id:102,name:'抗炎止痒'} ] },
                { id:11, name:'骨科与风湿', children:[ {id:111,name:'骨密度用药'}, {id:112,name:'抗风湿'} ] },
                { id:12, name:'中药', children:[ {id:121,name:'中成药'}, {id:122,name:'中药饮片'} ] }
            ];

            // 状态（提供示例数据避免空表）
            if (!Array.isArray(personalDrugs) || personalDrugs.length===0) {
                personalDrugs = [
                    { id:101, name:'阿司匹林肠溶片', code:'ASP001', spec:'100mg/片', form:'片剂', unit:'片', isBasic:true, usage:'口服', dosage:'100mg/次', frequency:'1次/日', price:'0.20', indications:'抗血小板聚集', contraindications:'消化道出血', categoryId:12 },
                    { id:102, name:'奥美拉唑肠溶胶囊', code:'OME003', spec:'20mg/粒', form:'胶囊', unit:'粒', isBasic:true, usage:'口服', dosage:'20mg/次', frequency:'1次/日', price:'1.50', indications:'胃溃疡', contraindications:'肝功能不全', categoryId:21 },
                    { id:103, name:'布洛芬片', code:'BL003', spec:'0.2g/片', form:'片剂', unit:'片', isBasic:true, usage:'口服', dosage:'0.2g/次', frequency:'3次/日', price:'0.30', indications:'发热镇痛', contraindications:'胃溃疡', categoryId:41 },
                    { id:104, name:'维生素C片', code:'VIT008', spec:'100mg/片', form:'片剂', unit:'片', isBasic:false, usage:'口服', dosage:'200mg/次', frequency:'3次/日', price:'0.05', indications:'维生素C缺乏', contraindications:'无', categoryId:91 }
                ];
            }
            let filtered = [...personalDrugs];
            let currentCategoryId = null; let currentPage = 1; let pageSize = 10; let totalPages = 1;
            let selected = new Set();
            const selectedCountEl = document.getElementById('selectedCount');

            // DOM
            const kw = document.getElementById('kw');
            const basicFilter = document.getElementById('basicFilter');
            const formFilter = document.getElementById('formFilter');
            const btnQuery = document.getElementById('btnQuery');
            const btnReset = document.getElementById('btnReset');
            const tbody = document.getElementById('tbody');
            const total = document.getElementById('total');
            const pages = document.getElementById('pages');
            const psel = document.getElementById('psel');
            const btnOk = document.getElementById('btnOk');
            const btnCancel = document.getElementById('btnCancel');
            const btnClose = document.getElementById('btnClose');

            // 分类
            const catList = document.getElementById('catList');
            const catKw = document.getElementById('catKw');

            function escapeHtml(str){ if (!str && str!==0) return ''; return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }

            function renderCategories(list = categories, level = 0, container = catList){
                if (container===catList) container.innerHTML = '';
                list.forEach(cat => {
                    const item = document.createElement('div');
                    item.className = 'category-item';
                    item.dataset.id = cat.id;
                    item.style.paddingLeft = (12 + level*16) + 'px';
                    item.innerHTML = `<span>${escapeHtml(cat.name)}</span>`;
                    if (currentCategoryId === cat.id) item.classList.add('active');
                    item.addEventListener('click', () => { currentCategoryId = cat.id; document.querySelectorAll('.category-item').forEach(i=>i.classList.remove('active')); item.classList.add('active'); applyFilter(); });
                    container.appendChild(item);
                    if (cat.children && cat.children.length){ renderCategories(cat.children, level+1, container); }
                });
            }

            function applyFilter(){
                const k = kw.value.trim().toLowerCase();
                const bf = basicFilter.value; const ff = formFilter.value;
                filtered = personalDrugs.filter(d => {
                    const matchKw = k ? (d.name.toLowerCase().includes(k) || d.code.toLowerCase().includes(k) || (d.indications||'').toLowerCase().includes(k)) : true;
                    const matchBasic = bf==='all' ? true : (bf==='yes' ? d.isBasic===true : d.isBasic===false);
                    const matchForm = ff==='all' ? true : (d.form===ff);
                    const matchCat = currentCategoryId ? isInCategory(d.categoryId, currentCategoryId) : true;
                    return matchKw && matchBasic && matchForm && matchCat;
                });
                currentPage = 1; renderTable();
            }

            function isInCategory(drugCatId, selectedCatId){
                // 判断药品的分类是否属于选中分类或其子级
                let found = false;
                (function dfs(nodes){
                    for (const n of nodes){
                        if (n.id === selectedCatId){
                            // 收集该分类及子分类id
                            const ids = []; (function collect(x){ ids.push(x.id); (x.children||[]).forEach(collect); })(n);
                            found = ids.includes(drugCatId); return;
                        }
                        if (n.children && n.children.length) dfs(n.children);
                        if (found) return;
                    }
                })(categories);
                return found;
            }

            function renderTable(){
                const start = (currentPage-1)*pageSize; const end = start + pageSize;
                const pageData = filtered.slice(start, end);
                tbody.innerHTML = '';
                if (pageData.length===0){
                    const tr = document.createElement('tr');
                    tr.innerHTML = `<td colspan="12" style="text-align:center; color:#767676; padding:16px;">暂无药品</td>`;
                    tbody.appendChild(tr);
                } else {
                    pageData.forEach(d=>{
                        const tr = document.createElement('tr');
                        const checked = selected.has(d.id) ? 'checked' : '';
                        tr.innerHTML = `
                            <td style="text-align:center;"><input class="checkbox pick" type="checkbox" data-id="${d.id}" ${checked}></td>
                            <td title="${escapeHtml(d.name)}">${escapeHtml(d.name)}</td>
                            <td>${escapeHtml(d.code)}</td>
                            <td>${escapeHtml(d.spec)}</td>
                            <td>${escapeHtml(d.form)}</td>
                            <td>${escapeHtml(d.unit)}</td>
                            <td>${d.isBasic?'是':'否'}</td>
                            <td>${escapeHtml(d.usage||'-')}</td>
                            <td>${escapeHtml(d.dosage||'-')}</td>
                            <td>${escapeHtml(d.frequency||'-')}</td>
                            <td>${escapeHtml(d.price||'-')}</td>
                            <td title="${escapeHtml(d.indications||'-')}">${escapeHtml(d.indications||'-')}</td>
                            <td title="${escapeHtml(d.contraindications||'-')}">${escapeHtml(d.contraindications||'-')}</td>
                            <td><a class="operation-link" data-op="detail" data-id="${d.id}">详情</a></td>
                        `;
                        tbody.appendChild(tr);
                    });
                }
                total.textContent = filtered.length;
                renderPages();
                updateOkButton();
                updateSelectedCount();
            }

            function renderPages(){
                const tp = Math.max(1, Math.ceil(filtered.length / pageSize));
                totalPages = tp; pages.innerHTML = '';
                let s = Math.max(1, currentPage-2), e = Math.min(tp, s+4); if (e-s<4 && tp>4) s = Math.max(1, e-4);
                for (let i=s; i<=e; i++){
                    const b = document.createElement('button'); b.textContent = i; b.className = i===currentPage? 'active':'';
                    b.addEventListener('click', ()=>{ currentPage=i; renderTable(); }); pages.appendChild(b);
                }
            }

            function updateOkButton(){ btnOk.disabled = selected.size===0; }
            function updateSelectedCount(){ if (selectedCountEl) selectedCountEl.textContent = selected.size; }

            // 事件
            btnQuery.addEventListener('click', applyFilter);
            btnReset.addEventListener('click', ()=>{ kw.value=''; basicFilter.value='all'; formFilter.value='all'; currentCategoryId=null; document.querySelectorAll('.category-item').forEach(i=>i.classList.remove('active')); filtered=[...personalDrugs]; currentPage=1; renderTable(); });
            kw.addEventListener('keypress', e=>{ if(e.key==='Enter') applyFilter(); });
            psel.addEventListener('change', ()=>{ pageSize=parseInt(psel.value,10); currentPage=1; renderTable(); });
            document.addEventListener('change', function(e){ const cb = e.target.closest('input.pick'); if(!cb) return; const id = parseInt(cb.getAttribute('data-id'),10); if (cb.checked) selected.add(id); else selected.delete(id); updateOkButton(); updateSelectedCount(); });
            // 详情操作
            document.addEventListener('click', function(e){
                const link = e.target.closest('a.operation-link');
                if (!link) return;
                const op = link.getAttribute('data-op');
                if (op === 'detail') {
                    alert('打开药品详情弹窗');
                }
            });

            // 分类搜索（简单包含过滤）
            catKw.addEventListener('input', ()=>{
                const text = catKw.value.trim().toLowerCase();
                catList.innerHTML='';
                function filterCats(nodes){
                    const res=[]; nodes.forEach(n=>{ const m = n.name.toLowerCase().includes(text); const kids = n.children? filterCats(n.children):[]; if (m || kids.length) res.push({ ...n, children: kids }); }); return res;
                }
                const view = text? filterCats(categories): categories;
                renderCategories(view);
            });

            btnCancel.addEventListener('click', ()=> { if (window.parent && window.parent !== window) { window.parent.postMessage({ type:'PICKER_CLOSE' }, '*'); } else { window.close(); } });
            btnClose.addEventListener('click', ()=> { if (window.parent && window.parent !== window) { window.parent.postMessage({ type:'PICKER_CLOSE' }, '*'); } else { window.close(); } });
            btnOk.addEventListener('click', ()=>{
                const picked = personalDrugs.filter(d=> selected.has(d.id));
                // 将选择结果发送给父页面
                if (window.opener && !window.opener.closed) {
                    if (window.opener.onDrugsPicked) {
                        window.opener.onDrugsPicked(picked);
                    } else if (window.opener.postMessage) {
                        window.opener.postMessage({ type:'DRUGS_PICKED', payload: picked }, '*');
                    }
                } else if (window.parent && window.parent !== window) {
                    window.parent.postMessage({ type:'DRUGS_PICKED', payload: picked }, '*');
                    window.parent.postMessage({ type:'PICKER_CLOSE' }, '*');
                } else {
                    window.close();
                }
            });

            // 初始化
            renderCategories();
            applyFilter();

            // 支持 iframe 模式下由父页面注入个人药品库数据
            window.addEventListener('message', function(e){
                const d = e && e.data;
                if (d && d.type === 'PERSONAL_DRUGS_INIT' && Array.isArray(d.payload)) {
                    // 仅当父页传入非空列表时才覆盖本地数据，避免被空数组清空导致无数据
                    if (d.payload.length > 0) {
                        personalDrugs = d.payload;
                        filtered = [...personalDrugs];
                        currentPage = 1;
                        renderTable();
                    }
                }
            });

            // 详情弹窗
            function openDetailDialog(drug){
                let overlay = document.getElementById('pickerDetailOverlay');
                if (!overlay) {
                    overlay = document.createElement('div');
                    overlay.id = 'pickerDetailOverlay';
                    overlay.className = 'modal-overlay';
                    document.body.appendChild(overlay);
                }
                overlay.style.display = 'flex';
                overlay.innerHTML = `
                    <div class="dialog">
                        <div class="modal-header">
                            <div class="modal-title">药品详情</div>
                            <button class="modal-close" id="closePickerDetail">×</button>
                        </div>
                        <div class="modal-body">
                            <div class="detail-grid">
                                <div class="detail-item"><div class="detail-label">药品名称</div><div class="detail-value">${escapeHtml(drug.name||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">药品编码</div><div class="detail-value">${escapeHtml(drug.code||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">规格</div><div class="detail-value">${escapeHtml(drug.spec||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">剂型</div><div class="detail-value">${escapeHtml(drug.form||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">单位</div><div class="detail-value">${escapeHtml(drug.unit||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">基本药物</div><div class="detail-value">${drug.isBasic?'是':'否'}</div></div>
                                <div class="detail-item"><div class="detail-label">常用用法</div><div class="detail-value">${escapeHtml(drug.usage||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">常用用量</div><div class="detail-value">${escapeHtml(drug.dosage||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">常用频次</div><div class="detail-value">${escapeHtml(drug.frequency||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">单价</div><div class="detail-value">${escapeHtml(drug.price||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">适应症</div><div class="detail-value">${escapeHtml(drug.indications||'-')}</div></div>
                                <div class="detail-item"><div class="detail-label">禁忌症</div><div class="detail-value">${escapeHtml(drug.contraindications||'-')}</div></div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-default" id="closePickerDetail2">关闭</button>
                        </div>
                    </div>`;
                const close = ()=>{ overlay.style.display='none'; };
                document.getElementById('closePickerDetail').addEventListener('click', close);
                document.getElementById('closePickerDetail2').addEventListener('click', close);
                overlay.addEventListener('click', (e)=>{ if (e.target===overlay) close(); });
            }
        })();
    </script>
</body>
</html>


